package com.wthink.hzgj.menu

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.R
import com.wthink.hzgj.data.domain.CheckinType
import com.wthink.hzgj.databinding.DialogKaoqingBinding
import com.wthink.hzgj.databinding.DialogLoginBinding
import com.wthink.hzgj.main.viewmodel.CheckinViewModel
import com.wthink.hzgj.util.DpUtil
import com.wthink.hzgj.util.setBackgroundAlpha
import com.wthink.hzgj.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginDialog {
    companion object {
        fun make(
            context: Context,
            container: ViewGroup,
            loginModel: LoginModel,
            activity: AppCompatActivity
        ): PopupWindow {
            val binding =
                DataBindingUtil.inflate<DialogLoginBinding>(
                    LayoutInflater.from(context),
                    R.layout.dialog_login,
                    container,
                    false
                ).apply {
                    this.viewModel = loginModel
                    this.lifecycleOwner = activity
                }

            return PopupWindow(
                binding.root,
                DpUtil.dp2px(context, 370f),
                DpUtil.dp2px(context, 260f),
                true
            ).apply {
                isOutsideTouchable = false
                isFocusable = true
                animationStyle = R.style.popupwindow_anim_style

                binding.root.findViewById<ImageView>(R.id.closeBtn).setOnClickListener {
                    dismiss()
                }

                binding.actBtn.setOnClickListener {
                    loginModel.viewModelScope.launch(Dispatchers.IO) {
                        val ret = loginModel.action()
                        withContext(Dispatchers.Main) {
                            if (ret == null) {
                                dismiss()
                            } else {
                                toast(context, ret)
                            }
                        }
                    }
                }
                setOnDismissListener {
                    activity.setBackgroundAlpha(1f)
                }
            }
        }
    }
}